﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using Samurai.MovieIndustry;
using Samurai.Infrastructure;
using System.Windows;
using System.Windows.Threading;
using System.ComponentModel;
using Samurai.Client.DataContexts;

namespace Samurai.Client.Commands
{
    public class PreviewMovieCommand : CommandBase
    {
        private EditMovieDataContext _context;

        public PreviewMovieCommand(EditMovieDataContext context)
        {
            _context = context;
        }

        protected override void InvokeExecute(object parameter)
        {
            var movieName = (string)parameter;

            var candidateMovie = new CandidateMovie() { Name = movieName, Path = _context.Path };

            InvokeLongOperationStart();                       

            var backgroundWorker = new BackgroundWorker();

            backgroundWorker.DoWork += BackgroundWorkerDoWork1;

            backgroundWorker.RunWorkerCompleted += BackgroundWorkerRunWorkerCompleted1;

            backgroundWorker.RunWorkerAsync(candidateMovie);            
        }

        void BackgroundWorkerRunWorkerCompleted1(
            object sender,
            RunWorkerCompletedEventArgs e)
        {
            var movie = (Movie)e.Result;

            InvokeLongOperationFinish();            
            _context.Movie = movie;
            _context.Image = movie.Image;
            _context.Title = movie.Title;
        }

        void BackgroundWorkerDoWork1(object sender, DoWorkEventArgs e)
        {
            var candidateMovie = (CandidateMovie)e.Argument;

            e.Result = new MovieDirector().Generate(candidateMovie);
        }
    }
}
